package com.huajx.tuopuda.client.udp.handler;

import com.alibaba.fastjson.JSON;
import com.huajx.core.Hboot;
import com.huajx.core.kit.HttpKit;
import com.huajx.tuopuda.client.udp.TuopudaDirect;
import com.huajx.tuopuda.client.udp.TuopudaException;
import com.huajx.tuopuda.client.udp.codec.auth.AppendAuthCodec;
import com.huajx.tuopuda.client.udp.codec.auth.ClearAuthCodec;
import com.huajx.tuopuda.client.udp.codec.setting.SetMachineInfoCodec;
import com.huajx.tuopuda.client.udp.config.SchoolConfig;
import com.huajx.tuopuda.client.udp.entity.Student;
import com.huajx.util.ObjectUtil;
import com.huajx.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.List;

/**
 * 9.2.3.8.3尾部加权限[109B]
 * <p>
 * 在指定位置增加: 也是最尾的记录值. 可能是最尾, 也可能是最新的位置. 前提是此位原记录应为FF(空,可加数据)
 *
 * @author: lisa 叶新华
 * @create: 2019-09-27 05:02
 */
public class AppendAuthHandler extends AbstractTuopudaHandler {
    private final static Logger logger = LoggerFactory.getLogger(AppendAuthHandler.class);
    private final static String get_card_id_url = SERVER_URL + "/di/personsattendance/getBigCardIds/";

    private static AppendAuthHandler me;

    public static AppendAuthHandler me() {
        if (me == null) {
            me = new AppendAuthHandler();
        }
        return me;
    }

    @Override
    public void send(String ip, int port, int sn) {

        SchoolConfig config = Hboot.config(SchoolConfig.class);

        if (config == null) {
            logger.warn("学校信息未配置，请在hboot.properties中配置");
            return;
        }

        if (!config.isInitial()) {
            logger.warn("该学校已经初始化学生信息。{} -- {}", config.getId(), config.getName());
            return;
        }

        String schoolId = config.getId();
        if (StrUtil.isBlank(schoolId)) {
            logger.warn("学校信息未配置，请在hboot.properties中配置hboot.school.id的值");
            return;
        }

        try {
            Object obj = HttpKit.get(get_card_id_url + config.getId());

            List<Student> studentList = JSON.parseArray((String) obj, Student.class);

            if (ObjectUtil.notEmpty(studentList)) {
                logger.info("获取学生记录: {}", studentList.size());

                clear(ip, port, sn);

                for (int i = 0; i < studentList.size(); i++) {
                    int cardId = studentList.get(i).getBigcardid();
                    send(ip, port, sn, cardId, i+1);
                }

                //设置基本信息
                sendAndReceive(ip, port, SetMachineInfoCodec.getInstance(sn).encode());
            }

        } catch (IOException | TuopudaException e) {

            e.printStackTrace();
            try {
                // 暂停
                Thread.sleep(3600000);
                // 递归执行，直至成功
                send(ip, port, sn);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
        }
    }

    public void send(String ip, int port, int sn,String carId) {

        SchoolConfig config = Hboot.config(SchoolConfig.class);

        if (config == null) {
            logger.warn("学校信息未配置，请在hboot.properties中配置");
            return;
        }

        if (!config.isInitial()) {
            logger.warn("该学校已经初始化学生信息。{} -- {}", config.getId(), config.getName());
            return;
        }

        String schoolId = config.getId();
        if (StrUtil.isBlank(schoolId)) {
            logger.warn("学校信息未配置，请在hboot.properties中配置hboot.school.id的值");
            return;
        }
       // send(ip, port, sn, cardId, i+1);
    }
    
    
    private void clear(String ip, int port, int sn) throws TuopudaException {
        //清除权限
        sendAndReceive(ip, port, ClearAuthCodec.getInstance(sn).encode());
        //设置基本信息
        sendAndReceive(ip, port, SetMachineInfoCodec.getInstance(sn).encode());

    }

    private void send(String ip, int port, int sn, int cardId, int index) {
        try {
            sendAndReceive(ip, port, encode(sn, TuopudaDirect.D_109D, cardId, index));
        } catch (TuopudaException e) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }

            send(ip, port, sn, cardId, index);
        }
    }

//    public void send(String ip, int port, int sn, int cardId, int pos) throws TuopudaException {
//        if(pos<=0) {
//            throw new TuopudaException("pos不能小于1");
//        }
//        byte[] bytes = encode(sn, TuopudaDirect.D_109B, cardId, pos);
//
//        sendAndReceive(ip, port, bytes);
//    }

    public byte[] encode(int sn, int function, int cardId, int pos) {
        return AppendAuthCodec.getInstance(sn, cardId, pos).encode();
    }
}
